
<template>
  <div class="dashboard">
    <!-- 欢迎动画层 -->
    <div v-if="showWelcome" class="welcome-layer">
      <div id="welcomeChart" style="width: 100vw; height: 100vh;"></div>
    </div>
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <el-icon><DataAnalysis /></el-icon>
        数据仪表板
      </h2>
      <p class="page-description">系统总体运行状况和数据统计概览</p>
      
    </div>

        <!-- 行政区划树卡片（已改为 区域名称/上级区域 模式） -->
    <el-card class="region-tree-card" shadow="hover">
      <template #header>
        <span class="card-title">
          <el-icon><Lightning /></el-icon>
          行政区划选择
        </span>
      </template>

      <div style="display: flex; align-items: center; justify-content: space-between; gap: 20px;">
        <!-- 基于区域名称的层级 -->
        <el-cascader
          v-model="selectedRegion"
          :options="regionOptions"
          :props="{ value: 'value', label: 'label', children: 'children' }"
          placeholder="请选择行政区划"
          clearable
          filterable
          style="width: 260px;"
          @change="handleRegionChange"
        />

        <!-- 中：显示选中区域 -->
        <div v-if="selectedRegionName" style="flex: 1; text-align: center; color: #606266;">
          <el-icon><Memo /></el-icon>
          当前选中区域：<b>{{ selectedRegionName }}</b>
        </div>

        <!-- 右：进入编辑按钮 -->
        <el-button
          type="primary"
          size="large"
          :disabled="!selectedRegionName"
          style="font-size: 15px; padding: 10px 22px;"
          @click="goToEditPage"
        >
          <el-icon><Edit /></el-icon>
          进入编辑
        </el-button>
      </div>
    </el-card>

<!-- 统计卡片区域 -->
<el-row :gutter="20" class="stats-row top-row" justify="space-between" align="middle">
  <!-- 卡片1：数据表总数 -->
  <el-col :xs="24" :sm="8" :md="8">
    <el-card class="stat-card total-tables">
      <div class="card-type">数据总表数</div>
      <div class="stat-content">
        <div class="stat-icon">
          <el-icon size="40"><Grid /></el-icon>
        </div>
        <div class="stat-info">
          <h3>{{ statistics.tableCount || 0 }}</h3>
        </div>
      </div>
    </el-card>
  </el-col>

  <!-- 卡片2：数据记录总数 -->
  <el-col :xs="24" :sm="8" :md="8">
    <el-card class="stat-card total-records">
      <div class="card-type">数据记录总条数</div>
      <div class="stat-content">
        <div class="stat-icon">
          <el-icon size="40"><Document /></el-icon>
        </div>
        <div class="stat-info">
          <h3>{{ statistics.totalRecords || 0 }}</h3>
        </div>
      </div>
    </el-card>
  </el-col>

  <!-- 系统状态放到右侧 -->
  <el-col :xs="24" :sm="8" :md="8">
    <el-card class="stat-card system-status" :class="{ online: systemOnline }">
      <div class="card-type">系统在线状态</div>
      <div class="stat-content">
        <div class="stat-icon">
          <el-icon size="40"><Monitor /></el-icon>
        </div>
        <div class="stat-info">
          <h3>{{ systemOnline ? '在线' : '离线' }}</h3>
        </div>
      </div>
    </el-card>
  </el-col>
</el-row>

<!-- 第二行：分类统计卡片 -->
<el-row :gutter="20" class="stats-row second-row">
  <!-- 建筑类 -->
  <el-col :xs="24" :sm="8" :md="8">
    <el-card class="stat-card category-card building">
      <div class="card-type">建筑类</div>
      <div class="stat-content">
        <div class="stat-icon">
          <el-icon size="40"><House /></el-icon>
        </div>
        <div class="stat-info">
          <!-- <h3>已录入 {{ statistics.tables['建筑基础信息表数量'] || 0 }} 个表</h3>
          <p>共 {{ statistics.tables['建筑基础信息'] || 0 }} 条记录</p> -->
          <h3>已录入 {{ statistics.tables['建筑类']?.表数量 || 0 }} 个表</h3>
          <p>共 {{ statistics.tables['建筑类']?.记录数 || 0 }} 条记录</p>
        </div>
      </div>
    </el-card>
  </el-col>

  <!-- 人员类 -->
  <el-col :xs="24" :sm="8" :md="8">
    <el-card class="stat-card category-card person">
      <div class="card-type">人员类</div>
      <div class="stat-content">
        <div class="stat-icon">
          <el-icon size="40"><User /></el-icon>
        </div>
        <div class="stat-info">
          <!-- <h3>已录入 {{ statistics.tables['人员信息表数量'] || 0 }} 个表</h3>
          <p>共 {{ statistics.tables['人员信息'] || 0 }} 条记录</p> -->
          <h3>已录入 {{ statistics.tables['人员类']?.表数量 || 0 }} 个表</h3>
          <p>共 {{ statistics.tables['人员类']?.记录数 || 0 }} 条记录</p>
        </div>
      </div>
    </el-card>
  </el-col>

  <!-- 设备类 -->
  <el-col :xs="24" :sm="8" :md="8">
    <el-card class="stat-card category-card device">
      <div class="card-type">设备类</div>
      <div class="stat-content">
        <div class="stat-icon">
          <el-icon size="40"><Cpu /></el-icon>
        </div>
        <div class="stat-info">
          <!-- <h3>已录入 {{ statistics.tables['设备信息表数量'] || 0 }} 个表</h3>
          <p>共 {{ statistics.tables['设备信息'] || 0 }} 条记录</p> -->
          <h3>已录入 {{ statistics.tables['设备类']?.表数量 || 0 }} 个表</h3>
          <p>共 {{ statistics.tables['设备类']?.记录数 || 0 }} 条记录</p>
        </div>
      </div>
    </el-card>
  </el-col>
</el-row>




    <!-- 快速操作面板 -->
    <el-row :gutter="20" class="quick-actions">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span class="card-title">
              <el-icon><Lightning /></el-icon>
              快速操作
            </span>
          </template>
          <div class="action-buttons">
            <!-- <el-button type="primary" size="large" @click="$router.push('/tables')">
              <el-icon><Grid /></el-icon>
              数据表结构管理
            </el-button>

            <el-button type="success" size="large" @click="$router.push('/data/建筑基础信息')">
              <el-icon><House /></el-icon>
              建筑基础信息
            </el-button> -->

            <el-button type="warning" size="large" @click="$router.push('/user')">
              <el-icon><Document /></el-icon>
              用户手册
            </el-button>

          </div>
        </el-card>
      </el-col>
    </el-row>
    
  </div>
</template>
<script setup>
// ---------- Vue 核心 ----------
import { ref, reactive, onMounted, computed, nextTick } from 'vue' 
import { onBeforeRouteUpdate, useRoute, useRouter } from 'vue-router' 

// ---------- Element Plus ----------
import { ElMessage } from 'element-plus'

// ---------- 图标 ----------
import {
  DataAnalysis, Grid, Document, House, Monitor,
  Memo, Refresh, View, Download, Lightning,
  OfficeBuilding, Shop, Edit
} from '@element-plus/icons-vue'

// ---------- API ----------
import { apiService } from '../api'

// ---------- ECharts ----------
import * as echarts from 'echarts'

// ---------- 欢迎动画状态 ----------
const showWelcome = ref(false) // 欢迎层显隐控制

// ---------- 路由 ----------
const router = useRouter()
const route = useRoute()

// ---------- 响应式数据 ----------
const selectedRegion = ref([])            // 当前选中的区域层级
const selectedRegionName = ref(null)      // 当前选中的最末级区域名
const regionOptions = ref([])             // 行政区划层级数据
const systemOnline = ref(false)
const dialogVisible = ref(false)          // 首页弹窗

const statistics = reactive({
  tableCount: 0,
  totalRecords: 0,
  tables: {}
})

// ---------- 计算属性 ----------
const tableStats = computed(() =>
  Object.entries(statistics.tables).map(([tableName, recordCount]) => ({
    tableName,
    recordCount
  }))
)
const buildingCount = computed(() => statistics.tables['建筑基础信息'] || 0)


// ---------- 方法区 ----------

/**
 * 将扁平数据构造成层级结构（基于 “区域名称 / 上级区域”）
 */
const buildRegionTree = (flatList) => {
  const nameMap = {}
  const tree = []

  flatList.forEach(item => {
    nameMap[item.区域名称] = { ...item, children: [] }
  })

  flatList.forEach(item => {
    const parentName = item.上级区域
    if (parentName && nameMap[parentName]) {
      nameMap[parentName].children.push(nameMap[item.区域名称])
    } else {
      tree.push(nameMap[item.区域名称])
    }
  })

  return tree
}

/**
 * 转换为 el-cascader 可用的数据结构
 */
const mapToCascader = (nodes) =>
  nodes.map(node => ({
    value: node.区域名称,
    label: node.区域名称,
    children: node.children?.length ? mapToCascader(node.children) : undefined
  }))

/**
 * 加载行政区划层级数据
 */
const loadRegionTree = async () => {
  try {
    const res = await apiService.getRegionTree()
    const rawData = Array.isArray(res.data) ? res.data : res
    const treeData = buildRegionTree(rawData)
    regionOptions.value = mapToCascader(treeData)
    console.log('行政区划层级数据：', regionOptions.value)
  } catch (err) {
    console.error('获取行政区划树失败:', err)
    ElMessage.error('获取行政区划树失败')
  }
}

/**
 * 当选择区域发生变化
 */
const handleRegionChange = (val) => {
  if (!val?.length) {
    selectedRegionName.value = null
    console.log('已清空选中区域')
    return
  }
  selectedRegionName.value = val[val.length - 1]
  console.log('当前选中区域：', selectedRegionName.value)
}

/**
 * 加载统计数据
 */
const loadStatistics = async () => {
  try {
    const data = await apiService.getStatistics()

    Object.assign(statistics, {
      tableCount: data.tableCount,
      totalRecords: data.totalRecords,
      tables: data.tables || {}
    })

    console.log('统计数据:', statistics.tables)
  } catch (err) {
    console.error('加载统计数据失败:', err)
    ElMessage.error('加载统计数据失败')
  }
}


/**
 * 检查系统状态
 */
const checkSystemStatus = async () => {
  try {
    await apiService.healthCheck()
    systemOnline.value = true
  } catch {
    systemOnline.value = false
  }
}

/**
 * 刷新所有数据
 */
const refreshData = async () => {
  await Promise.all([
    loadStatistics(),
    checkSystemStatus(),
    loadRegionTree()
  ])
}

/**
 * 进入编辑页
 */
const goToEditPage = () => {
  if (!selectedRegionName.value) {
    ElMessage.warning('请先选择一个具体的村级行政区！')
    return
  }

  router.push({
    path: '/edit',
    query: { region: selectedRegionName.value }
  })
}

/**
 * 欢迎动画绘制
 */
const showWelcomeChart = () => {
  const chartDom = document.getElementById('welcomeChart')
  if (!chartDom) return

  const myChart = echarts.init(chartDom)
  const option = {
    graphic: {
      elements: [
        {
          type: 'text',
          left: 'center',
          top: 'center',
          style: {
            text: '斋堂镇信息录入系统',
            fontSize: 80,
            fontWeight: 'bold',
            lineDash: [0, 200],
            lineDashOffset: 0,
            fill: 'transparent',
            stroke: '#000',
            lineWidth: 1
          },
          keyframeAnimation: {
            duration: 1500,
            loop: false,
            keyframes: [
              { percent: 0.7, style: { fill: 'transparent', lineDashOffset: 200, lineDash: [200, 0] } },
              { percent: 0.8, style: { fill: 'transparent' } },
              { percent: 1, style: { fill: 'black' } }
            ]
          }
        }
      ]
    }
  }

  myChart.setOption(option)

  // 动画播放完毕后自动关闭
  setTimeout(() => {
    showWelcome.value = false
    myChart.dispose()
  }, 1500)
}

// ---------- 生命周期 ----------
//  改进后的逻辑：只有“点击返回首页”时不显示动画
onMounted(async () => {
  const route = useRoute()
  const router = useRouter()

  const from = router.options.history.state.back // 有 back 值表示“从其他页面返回”

  if (!from) {
    //  首次进入或刷新：显示欢迎动画
    showWelcome.value = true
    await nextTick()
    showWelcomeChart()
  } else {
    // 返回首页：不显示动画
    showWelcome.value = false
  }

  await refreshData()
})
</script>


<style scoped>

.dashboard {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  height: 138px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
  gap: 16px;
}

.stat-icon {
  flex-shrink: 0;
}

.total-tables .stat-icon {
  color: #409EFF;
}

.total-records .stat-icon {
  color: #67C23A;
}

.buildings .stat-icon {
  color: #E6A23C;
}

.system-status .stat-icon {
  color: #F56C6C;
}

.system-status.online .stat-icon {
  color: #67C23A;
}

.stat-info h3 {
  margin: 0 0 4px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}
.region-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.stat-info p {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.detail-row {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.table-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-link {
  color: #409EFF;
  text-decoration: none;
  font-weight: 500;
}

.table-link:hover {
  text-decoration: underline;
}

.quick-actions {
  margin-bottom: 24px;
}

.action-buttons {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  display: flex;
  align-items: center;
  gap: 8px;
  height: 48px;
  padding: 0 24px;
  font-size: 16px;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
    justify-content: center;
  }
}
/* 调整两行卡片整体布局 */
.top-row {
  margin-bottom: 24px;
}

.second-row {
  margin-bottom: 32px;
}

/* 分类卡片颜色 */
.category-card.building .stat-icon {
  color: #E6A23C;
}

.category-card.person .stat-icon {
  color: #409EFF;
}

.category-card.device .stat-icon {
  color: #67C23A;
}
.card-type {
  font-size: 15px;
  font-weight: 600;
  color: #909399;
  margin-bottom: 6px;
  margin-left: 20px; /* 向右移动一点 */
}
.dashboard .el-card {
  border-radius: 12px !important;
  overflow: hidden;
}
.el-card {
  margin-bottom: 15px;
}
.welcome-layer {
  position: fixed;
  inset: 0;
  background-color: #f7f7f7;
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>
